import {
  Avatar,
  Button,
  Chip,
  Divider,
  Grid,
  IconButton,
  Paper,
  Slide,
  TextField,
  Typography,
  Zoom,
} from "@mui/material";
import { Box } from "@mui/system";
import { useMutation } from "@tanstack/react-query";
import cx from "clsx";
import React, { useState } from "react";
import { useContext } from "react";
import AddCircleOutlineIcon from "@mui/icons-material/AddCircleOutline";
import { useEffect } from "react";
import SearchAppBar from "../../../components/AppbarSearch";
import FindFail from "../../../components/FindFail";
import {
  COMMENT_LIST_URL,
  COMMENT_POST_URL,
  PUT_TAGS_URL,
} from "../../../constants/url";
import { postQueryFn } from "../../../query/postQueryFn";
import { Column, Row, Item } from "@mui-treasury/components/flex";
import { TitleContext } from "../../../router";
import { useDynamicAvatarStyles } from "@mui-treasury/styles/avatar/dynamic";
import CommentArea from "../../../components/CommentArea";
import { useTheme } from "@emotion/react";
import Loading from "../../../components/loading";
import { useSnackbar } from "notistack";
import { styled } from "@mui/material/styles";
import { mutateQueryFn } from "../../../query/mutateQueryFn";
const ListItem = styled("li")(({ theme }) => ({
  margin: theme.spacing(0.5),
}));

export default function Comment() {
  const titleContext = useContext(TitleContext);
  useEffect(() => {
    titleContext.setnowTitle(11);
  }, []);
  const [info, setInfo] = useState({});
  const [msg, setMsg] = useState();
  const [tid, setTid] = useState(true);
  const LetMeSay = (e) => {
    if (info.id) setTid(false);
    setTimeout(() => {
      setInfo(e);
      setTid(true);
    }, 290);
  };

  const {
    //评论接口
    isError: comError,
    isLoading: comLoading,
    isSuccess: comSuccess,
    data: comdata,
    mutate: comMutate,
  } = useMutation(["commentpos"], postQueryFn);

  const handlePost = () => {
    //
    if (msg == null || msg == "") {
      enqueueSnackbar("评论不能为空", { variant: "warning" });
      return;
    }
    comMutate({
      Key: [
        COMMENT_POST_URL,
        {
          params: {
            id: info.id,
          },
          useToken: true,
        },
      ],
      method: "put",
      params: {
        content: msg,
        title: "",
      },
    });
  };
  const { enqueueSnackbar } = useSnackbar();
  useEffect(() => {
    if (comSuccess) {
      //
      enqueueSnackbar("发送成功", { variant: "success" });
      setMsg("");
    }
  }, [comSuccess]);
  useEffect(() => {
    if (comError) {
      enqueueSnackbar("发送失败", { variant: "error" });
    }
  }, [comError]);

  const [tags, setTags] = useState([]);
  const [newTag, setNewTag] = useState("");
  const handleDelete = (id) => {
    setTags(tags.filter((val, index) => index != id));
  };

  const {
    isLoading: tagsLoading,
    isSuccess: tagsSuccess,
    mutate: tagsMutate,
  } = useMutation(["postTags"], mutateQueryFn);
  const postTags = () => {
    if (tags.length == 0) {
      enqueueSnackbar("请至少打一个标签", { variant: "warning" });
      return;
    }
    setTags([]);
    tagsMutate({
      url: PUT_TAGS_URL,
      method: "post",
      useToken: true,
      data: {
        tags: tags,
      },
      params: {
        userId: info.userId,
      },
    });
  };
  useEffect(() => {
    if (tagsSuccess) {
      enqueueSnackbar("发送成功", { variant: "success" });
    }
  }, [tagsSuccess]);
  return (
    <Box>
      <Grid container spacing={3}>
        <Grid item xs={12} md={5}>
          <CommentList id={info.id} LetMeSay={LetMeSay} />
        </Grid>
        <Grid item xs={12} md={7}>
          {info.id && (
            <Paper sx={{ padding: "10px 20px" }}>
              <Slide
                in={tid}
                appear={true}
                mountOnEnter
                unmountOnExit
                timeout={{ enter: 600, exit: 600 }}
                direction="right"
              >
                <Box
                  sx={{
                    position: "relative",
                    margin: "15px 0px",
                    display: "flex",
                    flexDirection: "row",
                    alignItems: "center",
                  }}
                >
                  <Avatar sx={{ width: 50, height: 50 }} src={info.avatar} />
                  <Box sx={{ marginLeft: 2 }}>
                    <Typography sx={{ fontWeight: "bold" }} variant="">
                      {info.name}
                    </Typography>
                    <Typography fontSize="small">{info?.className}</Typography>
                  </Box>
                  <Box flexGrow={1} />
                </Box>
              </Slide>
              <Box sx={{ marginTop: "30px" }}>
                {comLoading && <Loading />}
                {!comLoading && (
                  <div>
                    <Typography variant="h6">打标签</Typography>
                    <Box
                      sx={{
                        display: "flex",
                        flexDirection: "row",
                        alignItems: "center",
                      }}
                    >
                      <TextField
                        size="small"
                        sx={{ margin: 3 }}
                        value={newTag}
                        onChange={(e) => setNewTag(e.target.value)}
                      />
                      <IconButton
                        onClick={() => {
                          if (newTag == "") {
                            enqueueSnackbar("标签不能为空", {
                              variant: "warning",
                            });
                            return;
                          }
                          setTags([...tags, newTag]);
                          setNewTag("");
                        }}
                      >
                        <AddCircleOutlineIcon color="primary" />
                      </IconButton>
                    </Box>
                    <ChipTags handleDelete={handleDelete} val={tags} />
                    <Box
                      sx={{
                        display: "flex",
                        flexDirection: "column",
                        alignItems: "center",
                      }}
                    >
                      <Button
                        onClick={postTags}
                        variant="contained"
                        sx={{ marginTop: 3 }}
                      >
                        发送
                      </Button>
                    </Box>

                    <Typography variant="h6" sx={{ marginBottom: 3 }}>
                      评论
                    </Typography>

                    <CommentArea
                      handlePost={handlePost}
                      setMsg={setMsg}
                      msg={msg}
                      name={info.name}
                    />
                  </div>
                )}
              </Box>
              {/* </Slide> */}
            </Paper>
          )}
        </Grid>
      </Grid>
    </Box>
  );
}
const ChipTags = (props) => {
  return (
    <div>
      {props.val.length != 0 && (
        <Paper
          elevation={3}
          sx={{
            display: "flex",
            // justifyContent: "center",
            flexWrap: "wrap",

            listStyle: "none",
            p: 0.5,
            m: 0,
          }}
          component="ul"
        >
          {props.val.map((data, index) => {
            // let icon;

            return (
              <ListItem key={index}>
                <Chip
                  // icon={icon}
                  color="primary"
                  variant="outlined"
                  label={data}
                  onDelete={() => props.handleDelete(index)}
                />
              </ListItem>
            );
          })}
        </Paper>
      )}
    </div>
  );
};
const CommentList = (props) => {
  const { isError, data, isLoading, isSuccess, mutate } = useMutation(
    ["comment"],
    postQueryFn
  );
  const [name, setName] = useState();
  useEffect(() => {
    mutate({
      Key: [COMMENT_LIST_URL, { useToken: true }],
      method: "get",
    });
  }, []);

  const handleChange = (e) => {
    setName(e.target.value);
    mutate({
      Key: [
        COMMENT_LIST_URL,
        { useToken: true, params: { name: e.target.value } },
      ],
      method: "get",
    });
  };

  const theme = useTheme();
  const transitionDuration = {
    enter: theme.transitions.duration.enteringScreen,
    exit: theme.transitions.duration.leavingScreen,
  };

  return (
    <Box sx={{ zIndex: 10, position: "relative" }}>
      <Paper elevation={3} sx={{ padding: "20px 10px", borderRadius: "16px" }}>
        <Box
          sx={{
            display: "flex",
            flexDirection: "row",
            width: "100%",
            alignItems: "center",
            // opacity: ,
          }}
        >
          <Typography variant="h6">评论他</Typography>
          <Box flexGrow={1} />
          <Box>
            <SearchAppBar name={name} handleChange={handleChange} />
          </Box>
        </Box>
        <Box sx={{ minHeight: "200px" }}>
          {isLoading && <Loading />}
          {isSuccess && data?.data?.code == -1 && <FindFail />}
          {isSuccess &&
            !isLoading &&
            data?.data?.code != -1 &&
            data.data.data.map((value, key) => {
              return (
                <Zoom
                  in={value.id != props.id && value.id != props.tid}
                  appear={false}
                  mountOnEnter
                  unmountOnExit
                  direction="bottom"
                  timeout={{ enter: 290, exit: 290 }}
                  style={{
                    transitionDelay: `${
                      value.id != props.id ? transitionDuration.exit : 0
                    }ms`,
                  }}
                >
                  <Box>
                    <Item>
                      <Divider sx={{ margin: "10px 0" }} />
                      <Box
                        sx={{
                          margin: "15px 0px",
                          display: "flex",
                          flexDirection: "row",
                          alignItems: "center",
                        }}
                      >
                        <Avatar
                          sx={{ width: 50, height: 50 }}
                          src={value.avatar}
                        />
                        <Box sx={{ marginLeft: 2 }}>
                          <Typography sx={{ fontWeight: "bold" }} variant="">
                            {value.name}
                          </Typography>
                          <Typography fontSize="small">
                            {value?.className}
                          </Typography>
                        </Box>
                        <Box flexGrow={1} />
                        <Button
                          onClick={() => props.LetMeSay(value)}
                          variant="outlined"
                        >
                          评论
                        </Button>
                      </Box>
                    </Item>
                  </Box>
                </Zoom>
              );
            })}
        </Box>
      </Paper>
    </Box>
  );
};
